import { ref, unref } from 'vue'
import request from '@/api/common'
import { Form } from 'ant-design-vue'
import type { Ref } from 'vue'
import useBoolean from './useBoolean'
import { pickFormRequired } from '@/utils'
import { computed } from '@vue/reactivity'

const useAntForm = Form.useForm
interface Props {
  [key: string]: Array<any>;
}

export default function useForm<T extends object, Response extends object = object> (
  baseApi: string | ((...args: any) => Promise<Response>),
  rulesRef: Props | Ref<Props>
) {
  const { value: submitLoading, setValue: toggleLoading } = useBoolean()
  const { value: modal, setValue: toggleModal } = useBoolean()

  const formModel = ref(pickFormRequired<T & { id: string }>(unref(rulesRef)))

  const isAdd = computed(() => !formModel.value.id)
  const modalTitle = computed(() => isAdd.value ? '新增' : '编辑')

  function handleOpenModal (record: T = {} as T) {
    toggleModal(true)
    formModel.value = JSON.parse(JSON.stringify(record || {}))
  }

  const { resetFields, validate, validateInfos } = useAntForm(formModel, rulesRef, { })

  function submitForm () {
    return new Promise((resolve, reject) => {
      validate().then(async () => {
        toggleLoading(true)
        const submitAction = typeof baseApi === 'function'
          ? baseApi
          : request.setPath(baseApi)[isAdd.value ? 'post' : 'put']
        submitAction(formModel.value).then((res) => {
          resolve(res)
          toggleModal(false)
        }).catch(reject).finally(toggleLoading)
      })
    })
  }

  return {
    isAdd,
    modalTitle,
    formModel,
    modal,
    handleOpenModal,
    toggleModal,
    resetFields,
    submitForm,
    validate,
    validateInfos,
    submitLoading
  }
}
